<script setup lang="ts">
import {  ref, getCurrentInstance, watchEffect,nextTick,markRaw } from 'vue'
import { MoreHorizontalIcon } from 'lucide-vue-next'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'
import { Menubar, MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem } from '@/components/ui/menubar'
import { PlusIcon } from 'lucide-vue-next'
import { Input } from '@/components/ui/input'
import CommonIfNodeForm from '@/components/vue-flow/common-if-node-form.vue'
import { getChildrenToLLmJSONSchema, getChildrenToLLMoutputJSONSchema } from '@/lib/toJSONSchema'
import { LLMNodeData, LLMNodeEvents } from './index'
import storeMap from '@/pina/index'
import type { NodeProps, Edge } from '@vue-flow/core'
import { IfNodeRoot } from '@/components/vue-flow/nodes/types/form-types'
import { cloneDeep } from 'lodash'

const props = defineProps<NodeProps<LLMNodeData, LLMNodeEvents>>()
const ins = getCurrentInstance()
const insProxy = ins.proxy

const node = useNode()
const isEditTitle = ref(false)
const IfStore = storeMap.useIfStore()
let DLSData: IfNodeRoot = IfStore.nodes.find((item: any) => item.id == node.id)

let { title, labels, properties, description, branchs } = DLSData.data
const storeId = 'useIfStore'

const { removeNodes, nodes, addNodes, edges, getEdges, getNodes } = useVueFlow()
function handleClickDeleteBtn() {
  removeNodes(node.id)
}

function handleClickDuplicateBtn() {
  const { type, position, label, data } = node.node
  const newNode = {
    id: (nodes.value.length + 1).toString(),
    type,
    position: {
      x: position.x + 100,
      y: position.y + 100
    },
    label,
    data
  }
  addNodes(newNode)
}

const handleClickAddBtn = (priorityIndex: number) => {
  IfStore.addCondition(priorityIndex, node.id)
  // saveData()
}
const addBranch = () => {
  IfStore.add(node.id)
}
const handleRemoveFormDataItem = (id: string) => {
  const len = DLSData.data.branchs.length
  if (len == 1) return
  storeMap[storeId]().removeItem(id, node.id)
  
}

watchEffect(() => {
  if (node.connectedEdges && node.connectedEdges.value.length > 0) {
    if (node.node.data) {
      node.node.data = {
        //给node节点添加到json当中
        id: DLSData.id,
        type: DLSData.type,
        ...DLSData.data
      }
    }
  }
})
// 创建一个集合来存储所有相连的节点

const saveData = () => {
  // const sourceId = findConnectNodeByTarget(node.id, edges.value)
  // const sourceNode = nodes.value.find((node) => node.id === sourceId)
  // const sourceInput = LLM.template.formData.formItems.map((item:any)=>{
  //   return {
  //     "ref": "start_1",
  //     "name": "inputText",
  //     "category": "1",
  //     "value": "userText"
  //   }
  // })
  // const inputJson = getChildrenToLLmJSONSchema(IfStore.template.formData.formItems,IfStore.template.formData.ref)
  // const outputJson = getChildrenToLLMoutputJSONSchema(LLMoutput.template.formData.formItems)
  // node.node.data = {
  //给node节点添加到json当中
  // ...node.node.data,
  // "title": "模型节点",
  // input: inputJson,
  // output: outputJson
  // }
}
</script>

<template>
  <div class="w-[500px] rounded-sm border border-gray-200 bg-white p-3 shadow-md">
    <Handle type="target" :position="Position.Left" />
    <div class="flex flex-col gap-y-4">
      <div class="flex justify-between">
        <div class="flex gap-x-2">
          <img src="~@/assets/images/icon_Condition.png" class="mt-1 h-4 w-4" alt="Knowledge icon" />
          <div class="flex flex-col gap-y-1">
            <Input v-model="title" class="h-5" v-if="isEditTitle" @blur="() => (isEditTitle = false)" />
            <h3 class="text-base" v-else>{{ title }}</h3>
            <p class="text-sm text-gray-500">{{ description }}</p>
          </div>
        </div>
        <Menubar class="border-none">
          <menubar-menu>
            <menubar-trigger>
              <more-horizontal-icon />
            </menubar-trigger>
            <menubar-content>
              <menubar-item @click="handleClickDuplicateBtn"> 复制 </menubar-item>
              <menubar-item @click="handleClickDeleteBtn"> 删除 </menubar-item>
              <menubar-item @click="isEditTitle = true"> 重命名 </menubar-item>
            </menubar-content>
          </menubar-menu>
        </Menubar>
      </div>
      <div class="grid gap-y-3">
        <div class="if-title flex items-center justify-between">
          <span> 条件分支 </span>
          <p class="flex items-center text-xs text-primary" @click="addBranch">
            <plus-icon class="h-6 w-5 cursor-pointer text-primary"></plus-icon>
            <span> 新增分支 </span>
          </p>
        </div>
        <div v-for="(item, index) in DLSData.data.branchs" :key="item.id" class="relative">
          <Common-if-node-form
            :id="item.id"
            :key="item.id"
            :priorityIndex="index"
            :title="title"
            :labels="labels"
            :ItemInfo="item"
            :properties="properties"
            :description="description"
            @deleteBranchs="handleRemoveFormDataItem"
            @onClickAddBtn="handleClickAddBtn"
            :storeId="storeId"
          />
        </div>
        <div class="relative rounded-md bg-muted p-4">
          <div class="flex w-full items-center justify-between">
            <div class="flex items-center gap-x-2">
              <p class="text-xs">否则</p>
            </div>
          </div>
          <Handle type="source" :position="Position.Right" id="-else" />
        </div>
      </div>
    </div>
  </div>
</template>
